﻿using Dapper;
using Estsh.Core.Base;
using Estsh.Core.Dapper;
using Estsh.Core.Wms.IRepositories;
using Estsh.Core.Model.Result;
using Estsh.Core.Repositories;
using System.Collections;
using System.Data;
using System.Text;
using System.Security.Cryptography;
using System.Text.Json;
using Estsh.Core.Models;
using Estsh.Core.Model.Extend.Models;
using Newtonsoft.Json.Linq;
using Estsh.Core.Model.EnumUtil;
using Estsh.Core.Model.Extend;
using Newtonsoft.Json;

namespace Estsh.Core.Wms.Repositories
{
    public class MoveOrderRepository : BaseRepository<WmsMoveHeader>, IMoveOrderRepository
    {
        public MoveOrderRepository(DapperDbContext _dapperDbContext) : base(_dapperDbContext)
        {

        }

        /// <summary>
        /// 获取正在创建中的单据
        /// </summary>
        /// <returns></returns>
        public List<WmsMoveHeader> GetCreateingList()
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder SqlStringBuilder = new StringBuilder(1024);
                SqlStringBuilder.Append("SELECT * FROM dbo.wms_move_header a (nolock) ");
                SqlStringBuilder.Append(" WHERE a.order_status = @orderStatus AND enabled = 'Y' ");

                DynamicParameters parameters = new DynamicParameters();
                parameters.Add("@orderStatus", (int)WmsEnumUtil.MoveOrderStatus.CREATEING);

                List<WmsMoveHeader> moveOrderList = dbConn.Query<WmsMoveHeader>(SqlStringBuilder.ToString(), parameters).ToList();

                return moveOrderList;
            }
        }

        /// <summary>
        /// 根据单据类型获取此类型待处理的单据列表,如果单据类型为空，则获取全部类型
        /// </summary>
        /// <returns></returns>
        public List<WmsMoveHeader> GetMoveOrderList(int? orderType,string orderNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder SqlStringBuilder = new StringBuilder(1024);
                SqlStringBuilder.Append("SELECT * FROM dbo.wms_move_header a (nolock) ");

				SqlStringBuilder.Append(" WHERE a.order_status < @orderStatus AND enabled = 'Y' ");

                if (orderType != null && orderType > 0)//单据类型
                {
                    SqlStringBuilder.Append(" AND a.order_type = @orderType ");
                }
				if (orderNo.Length > 0 && orderNo != null)//单据号
				{
					SqlStringBuilder.Append(" AND a.order_no LIKE '%"+ orderNo + "%' ");
				}


				DynamicParameters parameters = new DynamicParameters();
                parameters.Add("@orderStatus", (int)WmsEnumUtil.MoveOrderStatus.COMPLETED);

                if (orderType != null && orderType > 0)
                {
                    parameters.Add("@orderType", orderType);
                }
				//if (orderNo.Length > 0 && orderNo != null)
				//{
				//	parameters.Add("@order_no", orderNo);
				//}
				List<WmsMoveHeader> moveOrderList = dbConn.Query<WmsMoveHeader>(SqlStringBuilder.ToString(), parameters).ToList();

                return moveOrderList;
            }
        }

        /// <summary>
        /// 根据单据号获取单据明细列表
        /// </summary>
        /// <returns></returns>
        public List<WmsMoveDetail> GetMoveDetailList(string orderNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder SqlStringBuilder = new StringBuilder(1024);
                SqlStringBuilder.Append("SELECT * FROM dbo.wms_move_detail (nolock) WHERE order_no = @orderNo AND enabled = 'Y' ");

                DynamicParameters parameters = new DynamicParameters();
                parameters.Add("@orderNo", orderNo);

                List<WmsMoveDetail> moveDetailList = dbConn.Query<WmsMoveDetail>(SqlStringBuilder.ToString(), parameters).ToList();

                return moveDetailList;
            }
        }

        /// <summary>
        /// 根据单据号和零件号获取单据明细
        /// </summary>
        /// <returns></returns>
        public WmsMoveDetail GetMoveDetail(string orderNo, string partNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder SqlStringBuilder = new StringBuilder(1024);
                SqlStringBuilder.Append("SELECT * ");
                SqlStringBuilder.Append("FROM dbo.wms_move_detail (nolock) ");
                SqlStringBuilder.Append("WHERE order_no = @orderNo ");
                SqlStringBuilder.Append("      AND part_no = @partNo ");
                SqlStringBuilder.Append("      AND enabled = 'Y' ");

                DynamicParameters parameters = new DynamicParameters();
                parameters.Add("@orderNo", orderNo);
                parameters.Add("@partNo", partNo);

                WmsMoveDetail moveDetail = dbConn.QueryFirstOrDefault<WmsMoveDetail>(SqlStringBuilder.ToString(), parameters);

                return moveDetail;
            }
        }

        /// <summary>
        /// 根据扫描的箱条码获取移动单据条码信息
        /// </summary>
        /// <param name="cartonNo"></param>
        /// <returns></returns>
        public WmsMoveSn GetMovesnInfo(string cartonNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                string result = string.Empty;

                StringBuilder sql = new StringBuilder(1024);
                sql.Append("select * from wms_move_sn (nolock) where carton_no=@carton_no and enabled='Y' ");
                DynamicParameters parameters = new DynamicParameters();
                parameters.Add("@carton_no", cartonNo);

                //List<SysStock> dt = dbConn.Query<SysStock>(sql.ToString(), parameters).ToList();
                return dbConn.QueryFirstOrDefault<WmsMoveSn>(sql.ToString(), parameters);
            }
        }

        /// <summary>
        /// 根据单据号获取单据条码列表
        /// </summary>
        /// <returns></returns>
        public List<WmsMoveSn> GetMoveSnList(string orderNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder SqlStringBuilder = new StringBuilder(1024);
                SqlStringBuilder.Append("SELECT * FROM dbo.wms_move_sn (nolock) WHERE order_no = @orderNo AND enabled = 'Y' ");

                DynamicParameters parameters = new DynamicParameters();
                parameters.Add("@orderNo", orderNo);

                List<WmsMoveSn> moveSnList = dbConn.Query<WmsMoveSn>(SqlStringBuilder.ToString(), parameters).ToList();

                return moveSnList;
            }
        }

        /// <summary>
        /// 根据单据号和箱条码获取单据条码
        /// </summary>
        /// <returns></returns>
        public WmsMoveSn GetMoveSn(string orderNo, string cartonNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder SqlStringBuilder = new StringBuilder(1024);
                SqlStringBuilder.Append("SELECT * ");
                SqlStringBuilder.Append("FROM dbo.wms_move_sn (nolock) ");
                SqlStringBuilder.Append("WHERE order_no = @orderNo ");
                SqlStringBuilder.Append("      AND carton_no = @cartonNo ");
                SqlStringBuilder.Append("      AND enabled = 'Y' ");

                DynamicParameters parameters = new DynamicParameters();
                parameters.Add("@orderNo", orderNo);
                parameters.Add("@cartonNo", cartonNo);

                WmsMoveSn moveSn = dbConn.QueryFirstOrDefault<WmsMoveSn>(SqlStringBuilder.ToString(), parameters);

                return moveSn;
            }
        }

        /// <summary>
        /// 处理扫描的箱条码
        /// </summary>
        /// <param name="cartonInfo"></param>
        /// <param name="moveDetail"></param>
        /// <returns></returns>
        public string DoCarton(SysStock_Extend cartonInfo, string orderNo, int orderType,
            string loginId, WmsMoveDetail moveDetail)
        {
            List<string> sqlStrings = new List<string>();
            List<DynamicParameters> parameterList = new List<DynamicParameters>();
            StringBuilder sql = new StringBuilder(1024);
            DynamicParameters parameters;

            // 单号为空则新增单据主表
            if (string.IsNullOrEmpty(orderNo))
            {
                if (orderType == (int)WmsEnumUtil.MoveOrderType.NC_IN_STOCK)
                {
                    orderNo = GetOrderNo("ShiftWarehouse", "M");//NC入库
                }
                else if (orderType == (int)WmsEnumUtil.MoveOrderType.NC_CONCESSION)
                {
                    orderNo = GetOrderNo("ShiftNCOutbound", "R");//NC让步接收单
                }
                else if (orderType == (int)WmsEnumUtil.MoveOrderType.NC_SCRAP)
                {
                    orderNo = GetOrderNo("ShiftNCScrap", "S");//NC报废单
                }
                else if (orderType == (int)WmsEnumUtil.MoveOrderType.NC_MOVE)
                {
                    orderNo = GetOrderNo("ShiftWarehouse", "M");//NC移库单
                }
                else if (orderType == (int)WmsEnumUtil.MoveOrderType.SUPPLIER_RETURN)
                {
                    orderNo = GetOrderNo("ShiftWarehouse", "M");//供应商退货单
                }
                else
                {
                    return "";
                }
                //插入单据主表-处理中
                sql.Remove(0, sql.Length);
                sql.Append("INSERT INTO dbo.wms_move_header ");
                sql.Append("( ");
                sql.Append("    order_no,order_type,order_status,ref_order_no,factory_id,factory_code, ");
                sql.Append("    enabled,create_userid,create_time,guid ");
                sql.Append(") ");
                sql.Append("VALUES ");
                sql.Append("(   @orderNo,@orderType,@orderStatus,@refOrderNo,@factoryId,@factoryCode, ");
                sql.Append("    @enabled,@createUserid,@createTime,@guid ");
                sql.Append(") ");

                parameters = new DynamicParameters();
                parameters.Add("@orderNo", orderNo);
                parameters.Add("@orderType", orderType);
                parameters.Add("@orderStatus", WmsEnumUtil.MoveOrderStatus.CREATEING);
                parameters.Add("@refOrderNo", cartonInfo.RelevanceOrder);
                parameters.Add("@factoryId", cartonInfo.FactoryId);
                parameters.Add("@factoryCode", cartonInfo.FactoryCode);
                parameters.Add("@enabled", WmsEnumUtil.Enabled.Y.ToString());
                parameters.Add("@createUserid", loginId);
                parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                parameters.Add("@guid", Guid.NewGuid());

                sqlStrings.Add(sql.ToString());
                parameterList.Add(parameters);
            }

            int itemNo = 0;
            if (moveDetail == null)
            {
                //插入单据明细表--需求数量
                object obj = this.GetOrderDetailCount(orderNo);
                if (obj == null)
                {
                    itemNo++;
                }
                else
                {
                    itemNo = int.Parse(obj.ToString());
                    itemNo++;
                }

                sql.Remove(0, sql.Length);
                sql.Append("INSERT INTO dbo.wms_move_detail ");
                sql.Append("(   order_no,item_no,part_id,part_no,part_spec,qty,pick_qty,out_qty,rec_qty,unit, ");
                sql.Append("    plan_date,plan_time,item_status,src_warehouse_id,src_warehouse_name,dest_warehouse_id, ");
                sql.Append("    dest_warehouse_name,src_zone_id,src_zone_name,dest_zone_id,dest_zone_name,src_erp_warehouse, ");
                sql.Append("    dest_erp_warehouse,factory_id,factory_code,enabled,create_userid,create_time,guid ");
                sql.Append(") ");
                sql.Append("VALUES ");
                sql.Append("(   @order_no,@item_no, ");
                sql.Append("    @part_id,@part_no,@part_spec,@qty,@pick_qty,@out_qty,@rec_qty,@unit, ");
                sql.Append("    @plan_date,@plan_time,@item_status,@src_warehouse_id,@src_warehouse_name,@dest_warehouse_id, ");
                sql.Append("    @dest_warehouse_name,@src_zone_id,@src_zone_name,@dest_zone_id,@dest_zone_name,@src_erp_warehouse, ");
                sql.Append("    @dest_erp_warehouse,@factory_id,@factory_code,@enabled,@create_userid,@create_time,@guid ");
                sql.Append("    ) ");


                parameters = new DynamicParameters();
                parameters.Add("@order_no", orderNo);
                parameters.Add("@item_no", itemNo);
                parameters.Add("@part_id", cartonInfo.PartId);
                parameters.Add("@part_no", cartonInfo.PartNo);
                parameters.Add("@part_spec", cartonInfo.PartSpec);
                parameters.Add("@qty", cartonInfo.Qty);
                parameters.Add("@pick_qty", 0);
                parameters.Add("@out_qty", 0);
                parameters.Add("@rec_qty", 0);
                parameters.Add("@unit", cartonInfo.Unit);
                parameters.Add("@plan_date", DateTime.Now.ToString("yyyy-MM-dd"));
                parameters.Add("@plan_time", string.Empty);
                parameters.Add("@item_status", WmsEnumUtil.MoveOrderDetailStatus.CREATE);
                parameters.Add("@src_warehouse_id", cartonInfo.WarehouseId);
                parameters.Add("@src_warehouse_name", cartonInfo.WarehouseName);
                parameters.Add("@dest_warehouse_id", 0);
                parameters.Add("@dest_warehouse_name", string.Empty);
                parameters.Add("@src_zone_id", cartonInfo.ZoneId);
                parameters.Add("@src_zone_name", cartonInfo.ZoneName);
                parameters.Add("@dest_zone_id", 0);
                parameters.Add("@dest_zone_name", string.Empty);
                parameters.Add("@src_erp_warehouse", cartonInfo.ErpWarehouse);
                parameters.Add("@dest_erp_warehouse", string.Empty);
                parameters.Add("@factory_id", cartonInfo.FactoryId);
                parameters.Add("@factory_code", cartonInfo.FactoryCode);
                parameters.Add("@enabled", WmsEnumUtil.Enabled.Y.ToString());
                parameters.Add("@create_userid", loginId);
                parameters.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                parameters.Add("@guid", Guid.NewGuid());

                sqlStrings.Add(sql.ToString());
                parameterList.Add(parameters);
            }
            else
            {
                //更新单据明细表--需求数量
                itemNo = int.Parse(moveDetail.ItemNo);

                sql.Remove(0, sql.Length);
                sql.Append("UPDATE dbo.wms_move_detail ");
                sql.Append("SET qty = qty + @qty, ");
                sql.Append("    update_userid = @updateUserid, ");
                sql.Append("    update_time = @updateTime ");
                sql.Append("WHERE order_no = @orderNo ");
                sql.Append("      AND part_id = @partId ");

                parameters = new DynamicParameters();
                parameters.Add("@orderNo", moveDetail.OrderNo);
                parameters.Add("@partId", cartonInfo.PartId);
                parameters.Add("@qty", cartonInfo.Qty);
                parameters.Add("@updateUserid", loginId);
                parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));

                sqlStrings.Add(sql.ToString());
                parameterList.Add(parameters);
            }
            //插入单据条码表
            sql.Remove(0, sql.Length);
            sql.Append("INSERT INTO dbo.wms_move_sn ");
            sql.Append("( ");
            sql.Append("    order_no,ref_order_no,item_no,part_id,part_no,part_spec, ");
            sql.Append("    carton_no,qty,unit,status,factory_id,factory_code,enabled, ");
            sql.Append("    create_userid,create_time,update_userid,update_time,guid ");
            sql.Append(") ");
            sql.Append("VALUES ");
            sql.Append("(   @orderNo,@refOrderNo,@itemNo,@partId,@partNo,@partSpec, ");
            sql.Append("    @cartonNo,@qty,@unit,@status,@factoryId,@factoryCode,@enabled, ");
            sql.Append("    @createUserid,@createTime,@updateUserid,@updateTime,@guid ");
            sql.Append("    ) ");

            parameters = new DynamicParameters();
            parameters.Add("@orderNo", orderNo);
            parameters.Add("@refOrderNo", cartonInfo.RelevanceOrder);
            parameters.Add("@itemNo", itemNo);
            parameters.Add("@partId", cartonInfo.PartId);
            parameters.Add("@partNo", cartonInfo.PartNo);
            parameters.Add("@partSpec", cartonInfo.PartSpec);
            parameters.Add("@cartonNo", cartonInfo.CartonNo);
            parameters.Add("@qty", cartonInfo.Qty);
            parameters.Add("@unit", cartonInfo.Unit);
            parameters.Add("@status", (int)WmsEnumUtil.MoveOrderSnStatus.CREATE);
            parameters.Add("@factoryId", cartonInfo.FactoryId);
            parameters.Add("@factoryCode", cartonInfo.FactoryCode);
            parameters.Add("@enabled", WmsEnumUtil.Enabled.Y.ToString());
            parameters.Add("@createUserid", loginId);
            parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
            parameters.Add("@updateUserid", loginId);
            parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
            parameters.Add("@guid", Guid.NewGuid());

            sqlStrings.Add(sql.ToString());
            parameterList.Add(parameters);

            if (orderType == (int)WmsEnumUtil.MoveOrderType.NC_IN_STOCK)
            {
                //更改条码表状态
                sql.Remove(0, sql.Length);
                sql.Append("UPDATE sys_stock ");
                sql.Append("SET status = @status, ");
                sql.Append("    update_userid = @updateUserid, ");
                sql.Append("    update_time = @updateTime ");
                sql.Append("WHERE carton_no = @cartonNo ");

                parameters = new DynamicParameters();
                parameters.Add("@cartonNo", cartonInfo.CartonNo);
                parameters.Add("@status", WmsEnumUtil.StockStatus.NC_QUARANTINE);
                parameters.Add("@updateUserid", loginId);
                parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));

                sqlStrings.Add(sql.ToString());
                parameterList.Add(parameters);

                //新增 sys_stock_trans 事务表
                sql.Remove(0, sql.Length);
                sql.Append("INSERT INTO [dbo].[sys_stock_trans] ");
                sql.Append("( ");
                sql.Append("    [trans_code],[carton_no],[part_id],[part_no],[part_spec],[src_locate_id],[src_locate_name],[dest_locate_id], ");
                sql.Append("    [dest_locate_name],[old_qty],[new_qty],[trans_qty],[old_status],[new_status],[old_qms_status],[new_qms_status],[unit], ");
                sql.Append("    [factory_id],[factory_code],[src_erp_warehouse],[dest_erp_warehouse],[src_warehouse_id],[src_warehouse_name], ");
                sql.Append("    [dest_warehouse_id],[dest_warehouse_name],[src_zone_id],[src_zone_name],[dest_zone_id],[dest_zone_name],[enabled], ");
                sql.Append("    [update_userid],[update_time], [create_userid],[create_time],[guid] ");
                sql.Append(") ");
                sql.Append("VALUES ");
                sql.Append("(@trans_code, @carton_no, @part_id, @part_no, @part_spec, @src_locate_id, @src_locate_name, @dest_locate_id, ");
                sql.Append(" @dest_locate_name, @old_qty, @new_qty, @trans_qty, @old_status, @new_status, @old_qms_status, @new_qms_status, @unit, ");
                sql.Append(" @factory_id, @factory_code, @src_erp_warehouse, @dest_erp_warehouse, @src_warehouse_id, @src_warehouse_name, ");
                sql.Append(" @dest_warehouse_id, @dest_warehouse_name, @src_zone_id, @src_zone_name, @dest_zone_id, @dest_zone_name, @enabled, ");
                sql.Append(" @update_userid, @update_time, @create_userid, @create_time, @guid) ");


                parameters = new DynamicParameters();
                parameters.Add("@trans_code", (int)WmsEnumUtil.TransType.QUARANTINE);
                parameters.Add("@carton_no", cartonInfo.CartonNo);
                parameters.Add("@part_id", cartonInfo.PartId);
                parameters.Add("@part_no", cartonInfo.PartNo);
                parameters.Add("@part_spec", cartonInfo.PartSpec);
                parameters.Add("@src_locate_id", cartonInfo.LocateId);
                parameters.Add("@src_locate_name", cartonInfo.LocateName);
                parameters.Add("@dest_locate_id", cartonInfo.LocateId);
                parameters.Add("@dest_locate_name", cartonInfo.LocateName);
                parameters.Add("@old_qty", cartonInfo.Qty);
                parameters.Add("@new_qty", cartonInfo.Qty);
                parameters.Add("@trans_qty", cartonInfo.Qty);
                parameters.Add("@old_status", cartonInfo.Status);
                parameters.Add("@new_status", (int)WmsEnumUtil.StockStatus.NC_QUARANTINE);
                parameters.Add("@old_qms_status", cartonInfo.QmsStatus);
                parameters.Add("@new_qms_status", cartonInfo.QmsStatus);
                parameters.Add("@unit", cartonInfo.Unit);
                parameters.Add("@factory_id", cartonInfo.FactoryId);
                parameters.Add("@factory_code", cartonInfo.FactoryCode);
                parameters.Add("@src_erp_warehouse", cartonInfo.ErpWarehouse);
                parameters.Add("@dest_erp_warehouse", cartonInfo.ErpWarehouse);
                parameters.Add("@src_warehouse_id", cartonInfo.WarehouseId);
                parameters.Add("@src_warehouse_name", cartonInfo.WarehouseName);
                parameters.Add("@dest_warehouse_id", cartonInfo.WarehouseId);
                parameters.Add("@dest_warehouse_name", cartonInfo.WarehouseName);
                parameters.Add("@src_zone_id", cartonInfo.ZoneId);
                parameters.Add("@src_zone_name", cartonInfo.ZoneName);
                parameters.Add("@dest_zone_id", cartonInfo.ZoneId);
                parameters.Add("@dest_zone_name", cartonInfo.ZoneName);
                parameters.Add("@enabled", cartonInfo.Enabled);
                parameters.Add("@update_userid", loginId);
                parameters.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                parameters.Add("@create_userid", loginId);
                parameters.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                parameters.Add("@guid", Guid.NewGuid());

                sqlStrings.Add(sql.ToString());
                parameterList.Add(parameters);
            }

            if (this.ExecuteTransaction(sqlStrings, parameterList))
            {
                return orderNo;
            }
            else
            {
                return "";
            }



        }

        /// <summary>
        /// 提交单据
        /// </summary>
        /// <param name="orderNo"></param>
        /// <param name="loginId"></param>
        /// <returns></returns>
        public bool OrderComplete(string orderNo, string loginId)
        {
            List<string> sqlStrings = new List<string>();
            List<DynamicParameters> parameterList = new List<DynamicParameters>();

            //更改单据主表-完成
            StringBuilder sql = new StringBuilder(1024);
            sql.Append("UPDATE dbo.wms_move_header ");
            sql.Append("SET order_status = @orderStatus, ");
            sql.Append("    update_userid = @updateUserid, ");
            sql.Append("    update_time = @updateTime ");
            sql.Append("WHERE order_no = @order_no ");
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("@orderStatus", WmsEnumUtil.MoveOrderStatus.COMPLETED);
            parameters.Add("@updateUserid", loginId);
            parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
            parameters.Add("@order_no", orderNo);

            sqlStrings.Add(sql.ToString());
            parameterList.Add(parameters);

            //更新单据明细表-完成
            sql.Remove(0, sql.Length);
            sql.Append("UPDATE dbo.wms_move_detail ");
            sql.Append("SET item_status = @itemStatus, ");
            sql.Append("    update_userid = @updateUserid, ");
            sql.Append("    update_time = @updateTime ");
            sql.Append("WHERE order_no = @orderNo ");
            sql.Append("      AND item_status < @itemStatus2 ");

            parameters = new DynamicParameters();
            parameters.Add("@itemStatus", WmsEnumUtil.MoveOrderDetailStatus.COMPLETED);
            parameters.Add("@updateUserid", loginId);
            parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
            parameters.Add("@orderNo", orderNo);
            parameters.Add("@itemStatus2", WmsEnumUtil.MoveOrderDetailStatus.COMPLETED);

            sqlStrings.Add(sql.ToString());
            parameterList.Add(parameters);

            return this.ExecuteTransaction(sqlStrings, parameterList);
        }

        /// <summary>
        /// 获取订单编号
        /// </summary>
        /// <returns></returns>
        public string GetOrderNo(string stockOrder, string p)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                DynamicParameters list = new DynamicParameters();
                list.Add("@order_type", stockOrder);
                list.Add("@order_prefix", p);
                list.Add("@order_no", null, DbType.String, ParameterDirection.Output, 50);

                var hashtable = dbConn.Execute("sys_create_orderno", list, commandType: CommandType.StoredProcedure);
                string result = list.Get<string>("@order_no");
                return result;
            }
        }

        /// <summary>
        /// 获取订单编号
        /// </summary>
        /// <returns></returns>
        public object GetOrderDetailCount(string orderNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder SqlStringBuilder = new StringBuilder(1024);
                SqlStringBuilder.Append("SELECT count(1) ");
                SqlStringBuilder.Append("FROM dbo.wms_move_detail (nolock) ");
                SqlStringBuilder.Append("WHERE order_no = @orderNo ");
                SqlStringBuilder.Append("      AND enabled = 'Y' ");

                DynamicParameters parameters = new DynamicParameters();
                parameters.Add("@orderNo", orderNo);

                return dbConn.ExecuteScalar(SqlStringBuilder.ToString(), parameters);
            }
        }

        /// <summary>
        /// 提交单据-单据创建
        /// </summary>
        /// <param name="orderNo"></param>
        /// <param name="loginId"></param>
        /// <returns></returns>
        public bool OrderCreated(string orderNo, string loginId)
        {
            List<string> sqlStrings = new List<string>();
            List<DynamicParameters> parameterList = new List<DynamicParameters>();

            //更改单据主表-创建
            StringBuilder sql = new StringBuilder(1024);
            sql.Append("UPDATE dbo.wms_move_header ");
            sql.Append("SET order_status = @orderStatus, ");
            sql.Append("    update_userid = @updateUserid, ");
            sql.Append("    update_time = @updateTime ");
            sql.Append("WHERE order_no = @order_no ");
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("@orderStatus", WmsEnumUtil.MoveOrderStatus.CREATE);
            parameters.Add("@updateUserid", loginId);
            parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
            parameters.Add("@order_no", orderNo);

            sqlStrings.Add(sql.ToString());
            parameterList.Add(parameters);

            return this.ExecuteTransaction(sqlStrings, parameterList);
        }

        /// <summary>
        /// 创建单据
        /// </summary>
        /// <param name="cartonInfo"></param>
        /// <param name="moveDetail"></param>
        /// <returns></returns>
        public void CreatePullOrder(string loginId, List<WmsMoveDetail> moveDetails)
        {
            List<string> sqlStrings = new List<string>();
            List<DynamicParameters> parameterList = new List<DynamicParameters>();
            StringBuilder sql = new StringBuilder(1024);
            DynamicParameters parameters;

            List<string> orders = moveDetails.Select(a => a.OrderNo).Distinct().ToList();

            foreach (var order in orders)
            {
                var details = moveDetails.Where(a => a.OrderNo.Equals(order)).ToList();

                var orderNo = GetOrderNo("ShiftProduction", "P");//生产领料
                //插入单据主表-处理中
                sql.Remove(0, sql.Length);
                sql.Append("INSERT INTO dbo.wms_move_header ");
                sql.Append("( ");
                sql.Append("    order_no,order_type,order_status,ref_order_no,factory_id,factory_code, ");
                sql.Append("    enabled,create_userid,create_time,guid ");
                sql.Append(") ");
                sql.Append("VALUES ");
                sql.Append("(   @orderNo,@orderType,@orderStatus,@refOrderNo,@factoryId,@factoryCode, ");
                sql.Append("    @enabled,@createUserid,@createTime,@guid ");
                sql.Append(") ");

                parameters = new DynamicParameters();
                parameters.Add("@orderNo", orderNo);
                parameters.Add("@orderType", WmsEnumUtil.MoveOrderType.PICK);
                parameters.Add("@orderStatus", WmsEnumUtil.MoveOrderStatus.CREATE);
                parameters.Add("@refOrderNo", order);
                parameters.Add("@factoryId", details[0].FactoryId);
                parameters.Add("@factoryCode", details[0].FactoryCode);
                parameters.Add("@enabled", WmsEnumUtil.Enabled.Y.ToString());
                parameters.Add("@createUserid", loginId);
                parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                parameters.Add("@guid", Guid.NewGuid());

                sqlStrings.Add(sql.ToString());
                parameterList.Add(parameters);

                var pdlineZone = GetPdlineZone(details[0].PdlineId);
                if (pdlineZone == null)
                {
                    pdlineZone = new SysPdlineZone();

                }
                int itemNo = 0;
                foreach (var detail in details)
                {
                    itemNo++;
                    sql.Remove(0, sql.Length);
                    sql.Append("INSERT INTO dbo.wms_move_detail ");
                    sql.Append("(   order_no,item_no,part_id,part_no,part_spec,qty,pick_qty,out_qty,rec_qty,unit, ");
                    sql.Append("    plan_date,plan_time,item_status,src_warehouse_id,src_warehouse_name,dest_warehouse_id, ");
                    sql.Append("    dest_warehouse_name,src_zone_id,src_zone_name,dest_zone_id,dest_zone_name,src_erp_warehouse, ");
                    sql.Append("    dest_erp_warehouse,factory_id,factory_code,enabled,create_userid,create_time,guid ");
                    sql.Append(") ");
                    sql.Append("VALUES ");
                    sql.Append("(   @order_no,@item_no, ");
                    sql.Append("    @part_id,@part_no,@part_spec,@qty,@pick_qty,@out_qty,@rec_qty,@unit, ");
                    sql.Append("    @plan_date,@plan_time,@item_status,@src_warehouse_id,@src_warehouse_name,@dest_warehouse_id, ");
                    sql.Append("    @dest_warehouse_name,@src_zone_id,@src_zone_name,@dest_zone_id,@dest_zone_name,@src_erp_warehouse, ");
                    sql.Append("    @dest_erp_warehouse,@factory_id,@factory_code,@enabled,@create_userid,@create_time,@guid ");
                    sql.Append("    ) ");

                    parameters = new DynamicParameters();
                    parameters.Add("@order_no", orderNo);
                    parameters.Add("@item_no", itemNo);
                    parameters.Add("@part_id", detail.PartId);
                    parameters.Add("@part_no", detail.PartNo);
                    parameters.Add("@part_spec", detail.PartSpec);
                    parameters.Add("@qty", detail.Qty);
                    parameters.Add("@pick_qty", 0);
                    parameters.Add("@out_qty", 0);
                    parameters.Add("@rec_qty", 0);
                    parameters.Add("@unit", detail.Unit);
                    parameters.Add("@plan_date", DateTime.Now.ToString("yyyy-MM-dd"));
                    parameters.Add("@plan_time", string.Empty);
                    parameters.Add("@item_status", WmsEnumUtil.MoveOrderDetailStatus.CREATE);
                    parameters.Add("@src_warehouse_id", 0);
                    parameters.Add("@src_warehouse_name", string.Empty);
                    parameters.Add("@dest_warehouse_id", pdlineZone.WarehouseId);
                    parameters.Add("@dest_warehouse_name", pdlineZone.WarehouseName);
                    parameters.Add("@src_zone_id", 0);
                    parameters.Add("@src_zone_name", string.Empty);
                    parameters.Add("@dest_zone_id", pdlineZone.ZoneId);
                    parameters.Add("@dest_zone_name", pdlineZone.ZoneName);
                    parameters.Add("@src_erp_warehouse", string.Empty);
                    parameters.Add("@dest_erp_warehouse", pdlineZone.ErpWarehouse);
                    parameters.Add("@factory_id", detail.FactoryId);
                    parameters.Add("@factory_code", detail.FactoryCode);
                    parameters.Add("@enabled", WmsEnumUtil.Enabled.Y.ToString());
                    parameters.Add("@create_userid", loginId);
                    parameters.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                    parameters.Add("@guid", Guid.NewGuid());

                    sqlStrings.Add(sql.ToString());
                    parameterList.Add(parameters);

                    sql.Remove(0, sql.Length);
                    sql.Append("UPDATE mes_work_order_part ");
                    sql.Append("SET pull_status = 20, ");
                    sql.Append("    update_userid = @updateUserid, ");
                    sql.Append("    update_time = @updateTime ");
                    sql.Append("WHERE order_no = @orderNo ");
                    sql.Append("      AND part_id = @partId ");


                    parameters = new DynamicParameters();
                    parameters.Add("@orderNo", detail.OrderNo);
                    parameters.Add("@partId", detail.PartId);
                    parameters.Add("@updateUserid", loginId);
                    parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));

                    sqlStrings.Add(sql.ToString());
                    parameterList.Add(parameters);

                }
                // 创建生产领料单
                this.ExecuteTransaction(sqlStrings, parameterList);
            }
        }

        /// <summary>
        /// 大件拣选创建单据
        /// </summary>
        /// <param name="loginId"></param>
        /// <param name="moveDetails"></param>
        public void CreatePullPickOrder(string loginId, List<WmsPullingOrderDetail> moveDetails, WmsPullingGroup pullingGroup)
        {
            List<string> sqlStrings = new List<string>();
            List<DynamicParameters> parameterList = new List<DynamicParameters>();
            StringBuilder sql = new StringBuilder(1024);
            DynamicParameters parameters;

            //List<string> orders = moveDetails.Select(a => a.OrderNo).Distinct().ToList();
            if (moveDetails.Count > pullingGroup.KittingQty)
            {
                var orderNo = GetOrderNo("PullPickNo", "JX");//大件拣选
                //插入PULL单据主表-处理中
                sql.Remove(0, sql.Length);
                sql.Append("INSERT INTO dbo.wms_pulling_order ");
                sql.Append("( ");
                sql.Append("    order_no,pulling_type,order_status,pulling_seq,group_code,group_name,work_order_no,cust_order_no, ");
                sql.Append("    pdline_id,pdline_code,factory_id,factory_code,enabled,create_userid,create_time, ");
                sql.Append("    update_userid,update_time,guid ");
                sql.Append(") ");
                sql.Append("VALUES ");
                sql.Append("( ");
                sql.Append("    @order_no,@pulling_type,@order_status,@pulling_seq,@group_code,@group_name,@work_order_no,@cust_order_no, ");
                sql.Append("    @pdline_id,@pdline_code,@factory_id,@factory_code,@enabled,@create_userid,@create_time, ");
                sql.Append("    @update_userid,@update_time,@guid ");
                sql.Append(") ");

                parameters = new DynamicParameters();
                parameters.Add("@order_no", orderNo);
                parameters.Add("@pulling_type", (int)WmsEnumUtil.PullGroupType.PRODUCT_JIT);
                parameters.Add("@order_status", (int)WmsEnumUtil.MoveOrderSnStatus.GENERATED);
                parameters.Add("@pulling_seq", 0);
                parameters.Add("@group_code", pullingGroup.GroupCode);
                parameters.Add("@group_name", pullingGroup.GroupName);
                parameters.Add("@work_order_no", moveDetails[0].OrderNo);
                parameters.Add("@cust_order_no", "");
                //parameters.Add("@printed", orderNo);
                //parameters.Add("@print_date", orderNo);
                //parameters.Add("@reprint_count", orderNo);
                parameters.Add("@pdline_id", moveDetails[0].PdlineId);
                parameters.Add("@pdline_code", moveDetails[0].PdlineCode);
                parameters.Add("@factory_id", moveDetails[0].FactoryId);
                parameters.Add("@factory_code", moveDetails[0].FactoryCode);
                parameters.Add("@enabled", "Y");
                parameters.Add("@create_userid", loginId);
                parameters.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                parameters.Add("@guid", Guid.NewGuid());
                parameters.Add("@update_userid", loginId);
                parameters.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));

                sqlStrings.Add(sql.ToString());
                parameterList.Add(parameters);

                var pdlineZone = GetPdlineZone(Convert.ToInt32(moveDetails[0].PdlineId));
                if (pdlineZone == null)
                {
                    pdlineZone = new SysPdlineZone();

                }
                for (int i = 0; i < pullingGroup.KittingQty; i++)
                {
                    sql.Remove(0, sql.Length);
                    sql.Append("INSERT INTO dbo.wms_pulling_order_detail ");
                    sql.Append("(   order_no,part_id,part_no,part_spec,qty,work_order_no,work_order_seq,cust_order_no,item_status,parent_part_id, ");
                    sql.Append("    parent_part_no,parent_part_spec,factory_id,factory_code,enabled,create_userid,create_time,update_userid, ");
                    sql.Append("    update_time,guid ");
                    sql.Append(") ");
                    sql.Append("VALUES ");
                    sql.Append("(   @order_no,@part_id,@part_no,@part_spec,@qty,@work_order_no,@work_order_seq,@cust_order_no,@item_status,@parent_part_id,");
                    sql.Append("    @parent_part_no,@parent_part_spec,@factory_id,@factory_code,@enabled,@create_userid,@create_time,@update_userid,");
                    sql.Append("    @update_time,@guid ");
                    sql.Append(") ");

                    parameters = new DynamicParameters();
                    parameters.Add("@order_no", orderNo);
                    parameters.Add("@part_id", moveDetails[i].PartId);
                    parameters.Add("@part_no", moveDetails[i].PartNo);
                    parameters.Add("@part_spec", moveDetails[i].PartSpec);
                    parameters.Add("@qty", moveDetails[i].Qty);
                    parameters.Add("@work_order_no", moveDetails[i].OrderNo);
                    parameters.Add("@work_order_seq", moveDetails[i].WorkOrderSeq);
                    parameters.Add("@cust_order_no", "");
                    parameters.Add("@item_status", (int)WmsEnumUtil.MoveOrderDetailStatus.CREATE);
                    parameters.Add("@parent_part_id", moveDetails[i].ParentPartId);
                    parameters.Add("@parent_part_no", moveDetails[i].ParentPartNo);
                    parameters.Add("@parent_part_spec", moveDetails[i].ParentPartSpec);
                    parameters.Add("@factory_id", moveDetails[i].FactoryId);
                    parameters.Add("@factory_code", moveDetails[i].FactoryCode);
                    parameters.Add("@enabled", "Y");
                    parameters.Add("@create_userid", loginId);
                    parameters.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                    parameters.Add("@guid", Guid.NewGuid());
                    parameters.Add("@update_userid", loginId);
                    parameters.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));

                    sqlStrings.Add(sql.ToString());
                    parameterList.Add(parameters);

                    sql.Remove(0, sql.Length);
                    sql.Append("UPDATE mes_work_order_part ");
                    sql.Append("SET pull_status = 20, ");
                    sql.Append("    update_userid = @updateUserid, ");
                    sql.Append("    update_time = @updateTime ");
                    sql.Append("WHERE ruid = @ruid ");


                    parameters = new DynamicParameters();
                    parameters.Add("@ruid", moveDetails[i].Ruid);
                    parameters.Add("@updateUserid", loginId);
                    parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));

                    sqlStrings.Add(sql.ToString());
                    parameterList.Add(parameters);

                }
            }
            this.ExecuteTransaction(sqlStrings, parameterList);

        }


        public void CreateSafetyPullOrder(string loginId, List<SysLocatePart> SysLocatePart)
        {
            List<string> sqlStrings = new List<string>();
            List<DynamicParameters> parameterList = new List<DynamicParameters>();
            StringBuilder sql = new StringBuilder(1024);
            DynamicParameters parameters;
             
            #region 处理无库存KT库位 拉动是零件无库存的产生一笔一个零件的拉动
            //var details0 = SysLocatePart.Where(a => a.Total2 ==0).ToList();

            //foreach (var item0 in details0)
            //{
            //    var orderNo = GetOrderNo("wms_linepickorderno", "M");//领料作业
            //    //插入单据主表-处理中
            //    sql.Remove(0, sql.Length);
            //    sql.Append("INSERT INTO dbo.wms_move_header ");
            //    sql.Append("( ");
            //    sql.Append("    order_no,order_type,order_status,ref_order_no,factory_id,factory_code, ");
            //    sql.Append("    enabled,create_userid,create_time,guid,wrong_sign,prepare_material ");
            //    sql.Append(") ");
            //    sql.Append("VALUES ");
            //    sql.Append("(   @orderNo,@orderType,@orderStatus,@refOrderNo,@factoryId,@factoryCode, ");
            //    sql.Append("    @enabled,@createUserid,@createTime,@guid,@wrong_sign,@prepare_material ");
            //    sql.Append(") ");

            //    parameters = new DynamicParameters();
            //    parameters.Add("@orderNo", orderNo);
            //    parameters.Add("@orderType", WmsEnumUtil.MoveOrderType.TRANSFER_ORDER);
            //    parameters.Add("@orderStatus", WmsEnumUtil.MoveOrderStatus.CREATE);
            //    parameters.Add("@refOrderNo", "安全库存拉动");
            //    parameters.Add("@factoryId", item0.FactoryId);
            //    parameters.Add("@factoryCode", item0.FactoryCode);
            //    parameters.Add("@enabled", WmsEnumUtil.Enabled.Y.ToString());
            //    parameters.Add("@createUserid", loginId);
            //    parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
            //    parameters.Add("@guid", Guid.NewGuid());
            //    parameters.Add("@wrong_sign", 1);
            //    parameters.Add("@prepare_material",2);//两步伐移库

            //    sqlStrings.Add(sql.ToString());
            //    parameterList.Add(parameters);

            //    sql.Remove(0, sql.Length);
            //    sql.Append("INSERT INTO dbo.wms_move_detail ");
            //    sql.Append("(   order_no,item_no,part_id,part_no,part_spec,qty,pick_qty,out_qty,rec_qty,unit, ");
            //    sql.Append("    plan_date,plan_time,item_status,src_warehouse_id,src_warehouse_name,dest_warehouse_id, ");
            //    sql.Append("    dest_warehouse_name,src_zone_id,src_zone_name,dest_zone_id,dest_zone_name,src_erp_warehouse, ");
            //    sql.Append("    dest_erp_warehouse,factory_id,factory_code,enabled,create_userid,create_time,guid ");
            //    sql.Append(") ");
            //    sql.Append("VALUES ");
            //    sql.Append("(   @order_no,@item_no, ");
            //    sql.Append("    @part_id,@part_no,@part_spec,@qty,@pick_qty,@out_qty,@rec_qty,@unit, ");
            //    sql.Append("    @plan_date,@plan_time,@item_status,@src_warehouse_id,@src_warehouse_name,@dest_warehouse_id, ");
            //    sql.Append("    @dest_warehouse_name,@src_zone_id,@src_zone_name,@dest_zone_id,@dest_zone_name,@src_erp_warehouse, ");
            //    sql.Append("    @dest_erp_warehouse,@factory_id,@factory_code,@enabled,@create_userid,@create_time,@guid ");
            //    sql.Append("    ) ");

            //    parameters = new DynamicParameters();
            //    parameters.Add("@order_no", orderNo);
            //    parameters.Add("@item_no", 1);
            //    parameters.Add("@part_id", item0.PartId);
            //    parameters.Add("@part_no", item0.PartNo);
            //    parameters.Add("@part_spec", item0.PartSpec);
            //    parameters.Add("@qty", item0.MaxQty - item0.SafetyQty);
            //    parameters.Add("@pick_qty", 0);
            //    parameters.Add("@out_qty", 0);
            //    parameters.Add("@rec_qty", 0);
            //    parameters.Add("@unit", "件");
            //    parameters.Add("@plan_date", DateTime.Now.ToString("yyyy-MM-dd"));
            //    parameters.Add("@plan_time", string.Empty);
            //    parameters.Add("@item_status", WmsEnumUtil.MoveOrderDetailStatus.CREATE);
            //    parameters.Add("@src_warehouse_id", 0);
            //    parameters.Add("@src_warehouse_name", string.Empty);
            //    parameters.Add("@dest_warehouse_id", item0.WarehouseId);
            //    parameters.Add("@dest_warehouse_name", item0.WarehouseName);
            //    parameters.Add("@src_zone_id", 0);
            //    parameters.Add("@src_zone_name", string.Empty);
            //    parameters.Add("@dest_zone_id", item0.ZoneId);
            //    parameters.Add("@dest_zone_name", item0.ZoneName);
            //    parameters.Add("@src_erp_warehouse", string.Empty);
            //    parameters.Add("@dest_erp_warehouse", item0.ErpWarehouse);
            //    parameters.Add("@factory_id", item0.FactoryId);
            //    parameters.Add("@factory_code", item0.FactoryCode);
            //    parameters.Add("@enabled", WmsEnumUtil.Enabled.Y.ToString());
            //    parameters.Add("@create_userid", loginId);
            //    parameters.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
            //    parameters.Add("@guid", Guid.NewGuid());

            //    sqlStrings.Add(sql.ToString());
            //    parameterList.Add(parameters);

            //    sql.Remove(0, sql.Length);
            //    sql.Append("update sys_locate_part set is_safety_pull=@is_safety_pull,safety_pull_order=@safety_pull_order where guid=@guid");

            //    parameters = new DynamicParameters();
            //    parameters.Add("@guid", item0.Guid);
            //    parameters.Add("@is_safety_pull", "1");
            //    parameters.Add("@safety_pull_order", orderNo);
            //    parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));

            //    sqlStrings.Add(sql.ToString());
            //    parameterList.Add(parameters);
            //}
            #endregion

            //处理有库存KT库位
            //SysLocatePart = SysLocatePart.Where(a => a.Total2 != 0).ToList();
            List<string> orders = SysLocatePart.Select(a => a.ZoneName).Distinct().ToList();

            foreach (var order in orders)
            {
                var details = SysLocatePart.Where(a => a.ZoneName.Equals(order)).ToList();

                var orderNo = GetOrderNo("wms_linepickorderno", "M");//领料作业
                                                                     //插入单据主表-处理中
                sql.Remove(0, sql.Length);
                sql.Append("INSERT INTO dbo.wms_move_header ");
                sql.Append("( ");
                sql.Append("    order_no,order_type,order_status,ref_order_no,factory_id,factory_code, ");
                sql.Append("    enabled,create_userid,create_time,guid,wrong_sign,prepare_material ");
                sql.Append(") ");
                sql.Append("VALUES ");
                sql.Append("(   @orderNo,@orderType,@orderStatus,@refOrderNo,@factoryId,@factoryCode, ");
                sql.Append("    @enabled,@createUserid,@createTime,@guid,@wrong_sign,@prepare_material ");
                sql.Append(") ");

                parameters = new DynamicParameters();
                parameters.Add("@orderNo", orderNo);
                parameters.Add("@orderType", WmsEnumUtil.MoveOrderType.PICK);
                parameters.Add("@orderStatus", WmsEnumUtil.MoveOrderStatus.CREATE);
                parameters.Add("@refOrderNo", "安全库存拉动");
                parameters.Add("@factoryId", details[0].FactoryId);
                parameters.Add("@factoryCode", details[0].FactoryCode);
                parameters.Add("@enabled", WmsEnumUtil.Enabled.Y.ToString());
                parameters.Add("@createUserid", loginId);
                parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                parameters.Add("@guid", Guid.NewGuid());
                parameters.Add("@wrong_sign", 0);
                parameters.Add("@prepare_material", 2); //两步伐调拨

                sqlStrings.Add(sql.ToString());
                parameterList.Add(parameters);

                //var pdlineZone = GetPdlineZone(details[0].PdlineId);
                //if (pdlineZone == null)
                //{
                //    pdlineZone = new SysPdlineZone();

                //}
                int itemNo = 0;
                foreach (var detail in details)
                {
                    itemNo++;
                    sql.Remove(0, sql.Length);
                    sql.Append("INSERT INTO dbo.wms_move_detail ");
                    sql.Append("(   order_no,item_no,part_id,part_no,part_spec,qty,pick_qty,out_qty,rec_qty,unit, ");
                    sql.Append("    plan_date,plan_time,item_status,src_warehouse_id,src_warehouse_name,dest_warehouse_id, ");
                    sql.Append("    dest_warehouse_name,src_zone_id,src_zone_name,dest_zone_id,dest_zone_name,src_erp_warehouse, ");
                    sql.Append("    dest_erp_warehouse,factory_id,factory_code,enabled,create_userid,create_time,dest_locate_id,dest_locate_name,guid ");
                    sql.Append(") ");
                    sql.Append("VALUES ");
                    sql.Append("(   @order_no,@item_no, ");
                    sql.Append("    @part_id,@part_no,@part_spec,@qty,@pick_qty,@out_qty,@rec_qty,@unit, ");
                    sql.Append("    @plan_date,@plan_time,@item_status,@src_warehouse_id,@src_warehouse_name,@dest_warehouse_id, ");
                    sql.Append("    @dest_warehouse_name,@src_zone_id,@src_zone_name,@dest_zone_id,@dest_zone_name,@src_erp_warehouse, ");
                    sql.Append("    @dest_erp_warehouse,@factory_id,@factory_code,@enabled,@create_userid,@create_time,@dest_locate_id,@dest_locate_name,@guid ");
                    sql.Append("    ) ");

                    parameters = new DynamicParameters();
                    parameters.Add("@order_no", orderNo);
                    parameters.Add("@item_no", itemNo);
                    parameters.Add("@part_id", detail.PartId);
                    parameters.Add("@part_no", detail.PartNo);
                    parameters.Add("@part_spec", detail.PartSpec);
                    parameters.Add("@qty", detail.MaxQty - detail.SafetyQty);
                    parameters.Add("@pick_qty", 0);
                    parameters.Add("@out_qty", 0);
                    parameters.Add("@rec_qty", 0);
                    parameters.Add("@unit", "件");
                    parameters.Add("@plan_date", DateTime.Now.ToString("yyyy-MM-dd"));
                    parameters.Add("@plan_time", string.Empty);
                    parameters.Add("@item_status", WmsEnumUtil.MoveOrderDetailStatus.CREATE);
                    parameters.Add("@src_warehouse_id", 0);
                    parameters.Add("@src_warehouse_name", string.Empty);
                    parameters.Add("@dest_warehouse_id", detail.WarehouseId);
                    parameters.Add("@dest_warehouse_name", detail.WarehouseName);
                    parameters.Add("@src_zone_id", 0);
                    parameters.Add("@src_zone_name", string.Empty);
                    parameters.Add("@dest_zone_id", detail.ZoneId);
                    parameters.Add("@dest_zone_name", detail.ZoneName);
                    parameters.Add("@src_erp_warehouse", string.Empty);
                    parameters.Add("@dest_erp_warehouse", detail.ErpWarehouse);
                    parameters.Add("@factory_id", detail.FactoryId);
                    parameters.Add("@factory_code", detail.FactoryCode);
                    parameters.Add("@enabled", WmsEnumUtil.Enabled.Y.ToString());
                    parameters.Add("@create_userid", loginId);
                    parameters.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                    parameters.Add("@dest_locate_id", detail.LocateId);
                    parameters.Add("@dest_locate_name", detail.LocateName);
                    parameters.Add("@guid", Guid.NewGuid());

                    sqlStrings.Add(sql.ToString());
                    parameterList.Add(parameters);

                    sql.Remove(0, sql.Length);
                    sql.Append("update sys_locate_part set is_safety_pull=@is_safety_pull,safety_pull_order=@safety_pull_order where guid=@guid");

                    parameters = new DynamicParameters();
                    parameters.Add("@guid", detail.Guid);
                    parameters.Add("@is_safety_pull", "1");
                    parameters.Add("@safety_pull_order", orderNo);
                    parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));

                    sqlStrings.Add(sql.ToString());
                    parameterList.Add(parameters);

                }

            }
            // 创建生产领料单
            this.ExecuteTransaction(sqlStrings, parameterList);
        }

        public void ChangeSafety(List<WmsMoveHeader> header)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                List<string> sqlStrings = new List<string>();
                List<DynamicParameters> parameterList = new List<DynamicParameters>();
                StringBuilder sql = new StringBuilder(1024);
                DynamicParameters parameters;

                var details0 = header.Where(a => !a.Qty.Equals("0")).ToList();

                foreach (var item in details0)
                {
                    sql.Remove(0, sql.Length);
                    sql.Append("update wms_move_header set wrong_sign=0 where guid=@guid");

                    parameters = new DynamicParameters();
                    parameters.Add("@guid", item.Guid);

                    sqlStrings.Add(sql.ToString());
                    parameterList.Add(parameters);
                }
                this.ExecuteTransaction(sqlStrings, parameterList);

            }
        }
        /// <summary>
        /// 根据产线ID获取产线库区关系信息
        /// </summary>
        /// <param name="pdlineId"></param>
        /// <returns></returns>
        private SysPdlineZone GetPdlineZone(int pdlineId)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder SqlStringBuilder = new StringBuilder(1024);
                SqlStringBuilder.Append("SELECT top 1 *,z.erp_warehouse FROM [dbo].[sys_pdline_zone] pz (nolock) ");
                SqlStringBuilder.Append("JOIN dbo.sys_zone z (nolock) ON pz.zone_id = z.zone_id ");

                SqlStringBuilder.Append("WHERE pz.pdline_id = @pdlineId ");
                SqlStringBuilder.Append("      AND pz.busi_type = @busiType ");
                SqlStringBuilder.Append("      AND pz.enabled = 'Y' ");

                DynamicParameters parameters = new DynamicParameters();
                parameters.Add("@pdlineId", pdlineId);
                parameters.Add("@busiType", WmsEnumUtil.PdlineZoneBusiType.BIG_PART_PULL);

                var result = dbConn.QueryFirstOrDefault<SysPdlineZone>(SqlStringBuilder.ToString(), parameters);

                return result;
            }
        }

        /// <summary>
        /// 获取库存数量（根据零件+库区）
        /// </summary>
        /// <param name="partId"></param>
        /// <param name="zoneId"></param>
        /// <returns></returns>
        public decimal GetPickQty(int partId, int zoneId)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();

                StringBuilder sql = new StringBuilder(1024);
                sql.Append("SELECT SUM(b.qty - b.out_qty) FROM dbo.wms_move_header a (nolock) ");
                sql.Append("	JOIN dbo.wms_move_detail b (nolock) ON a.order_no = b.order_no ");
                sql.Append("WHERE a.order_type = @orderType ");
                sql.Append("	AND a.order_status < @orderStatus ");
                sql.Append("	AND b.part_id = @partId ");
                sql.Append("	AND b.dest_zone_id = @destZoneId ");
                sql.Append("	AND b.qty>b.out_qty ");
                sql.Append("	AND b.item_status < @itemStatus ");

                DynamicParameters parameters = new DynamicParameters();
                parameters.Add("@orderType", WmsEnumUtil.MoveOrderType.PICK);
                parameters.Add("@orderStatus", WmsEnumUtil.MoveOrderStatus.COMPLETED);
                parameters.Add("@partId", partId);
                parameters.Add("@destZoneId", zoneId);
                parameters.Add("@itemStatus", WmsEnumUtil.MoveOrderDetailStatus.COMPLETED);

                var result = dbConn.ExecuteScalar(sql.ToString(), parameters);

                if (result == null)
                {
                    return 0;
                }
                else
                {
                    return decimal.Parse(result.ToString());
                }
            }

        }

        /// <summary>
        /// 创建单据
        /// </summary>
        /// <returns></returns>
        public void CreatePullOrder(string loginId, List<WmsMoveDetail> moveDetails, SysPdlineZone pdlineZone)
        {
            List<string> sqlStrings = new List<string>();
            List<DynamicParameters> parameterList = new List<DynamicParameters>();
            StringBuilder sql = new StringBuilder(1024);
            DynamicParameters parameters;

            var orderNo = GetOrderNo("ShiftProduction", "P");//生产领料
                                                             //插入单据主表-处理中
            sql.Remove(0, sql.Length);
            sql.Append("INSERT INTO dbo.wms_move_header ");
            sql.Append("( ");
            sql.Append("    order_no,order_type,order_status,ref_order_no,factory_id,factory_code, ");
            sql.Append("    enabled,create_userid,create_time,guid ");
            sql.Append(") ");
            sql.Append("VALUES ");
            sql.Append("(   @orderNo,@orderType,@orderStatus,@refOrderNo,@factoryId,@factoryCode, ");
            sql.Append("    @enabled,@createUserid,@createTime,@guid ");
            sql.Append(") ");

            parameters = new DynamicParameters();
            parameters.Add("@orderNo", orderNo);
            parameters.Add("@orderType", WmsEnumUtil.MoveOrderType.PICK);
            parameters.Add("@orderStatus", WmsEnumUtil.MoveOrderStatus.CREATE);
            parameters.Add("@refOrderNo", string.Empty);
            parameters.Add("@factoryId", moveDetails[0].FactoryId);
            parameters.Add("@factoryCode", moveDetails[0].FactoryCode);
            parameters.Add("@enabled", WmsEnumUtil.Enabled.Y.ToString());
            parameters.Add("@createUserid", loginId);
            parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
            parameters.Add("@guid", Guid.NewGuid());

            sqlStrings.Add(sql.ToString());
            parameterList.Add(parameters);

            int itemNo = 0;
            foreach (var detail in moveDetails)
            {
                itemNo++;
                sql.Remove(0, sql.Length);
                sql.Append("INSERT INTO dbo.wms_move_detail ");
                sql.Append("(   order_no,item_no,part_id,part_no,part_spec,qty,pick_qty,out_qty,rec_qty,unit, ");
                sql.Append("    plan_date,plan_time,item_status,src_warehouse_id,src_warehouse_name,dest_warehouse_id, ");
                sql.Append("    dest_warehouse_name,src_zone_id,src_zone_name,dest_zone_id,dest_zone_name,src_erp_warehouse, ");
                sql.Append("    dest_erp_warehouse,factory_id,factory_code,enabled,create_userid,create_time,guid ");
                sql.Append(") ");
                sql.Append("VALUES ");
                sql.Append("(   @order_no,@item_no, ");
                sql.Append("    @part_id,@part_no,@part_spec,@qty,@pick_qty,@out_qty,@rec_qty,@unit, ");
                sql.Append("    @plan_date,@plan_time,@item_status,@src_warehouse_id,@src_warehouse_name,@dest_warehouse_id, ");
                sql.Append("    @dest_warehouse_name,@src_zone_id,@src_zone_name,@dest_zone_id,@dest_zone_name,@src_erp_warehouse, ");
                sql.Append("    @dest_erp_warehouse,@factory_id,@factory_code,@enabled,@create_userid,@create_time,@guid ");
                sql.Append("    ) ");

                parameters = new DynamicParameters();
                parameters.Add("@order_no", orderNo);
                parameters.Add("@item_no", itemNo);
                parameters.Add("@part_id", detail.PartId);
                parameters.Add("@part_no", detail.PartNo);
                parameters.Add("@part_spec", detail.PartSpec);
                parameters.Add("@qty", detail.Qty);
                parameters.Add("@pick_qty", 0);
                parameters.Add("@out_qty", 0);
                parameters.Add("@rec_qty", 0);
                parameters.Add("@unit", detail.Unit);
                parameters.Add("@plan_date", DateTime.Now.ToString("yyyy-MM-dd"));
                parameters.Add("@plan_time", string.Empty);
                parameters.Add("@item_status", WmsEnumUtil.MoveOrderDetailStatus.CREATE);
                parameters.Add("@src_warehouse_id", 0);
                parameters.Add("@src_warehouse_name", string.Empty);
                parameters.Add("@dest_warehouse_id", pdlineZone.WarehouseId);
                parameters.Add("@dest_warehouse_name", pdlineZone.WarehouseName);
                parameters.Add("@src_zone_id", 0);
                parameters.Add("@src_zone_name", string.Empty);
                parameters.Add("@dest_zone_id", pdlineZone.ZoneId);
                parameters.Add("@dest_zone_name", pdlineZone.ZoneName);
                parameters.Add("@src_erp_warehouse", string.Empty);
                parameters.Add("@dest_erp_warehouse", pdlineZone.ErpWarehouse);
                parameters.Add("@factory_id", detail.FactoryId);
                parameters.Add("@factory_code", detail.FactoryCode);
                parameters.Add("@enabled", WmsEnumUtil.Enabled.Y.ToString());
                parameters.Add("@create_userid", loginId);
                parameters.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                parameters.Add("@guid", Guid.NewGuid());

                sqlStrings.Add(sql.ToString());
                parameterList.Add(parameters);
            }
            // 创建生产领料单
            this.ExecuteTransaction(sqlStrings, parameterList);

        }


    }
}
